#!/usr/bin/python
'''
Summarizes relative hits of mirbase entries.
'''

import sys
from operator import itemgetter, attrgetter


# Get parameters.
total_file = sys.argv[1]
entry_file = sys.argv[2]

# Read in totals.
fin = open(total_file,"rb")
lines = fin.readlines()
fin.close()

mirbase = {}
for line in lines:
	tmp = line.strip().split()
	mirbase[tmp[1]] = [int(tmp[0]),0]

# Read in GFF and build distribution.
fin = open(entry_file,"rb")
lines = fin.readlines()
fin.close()

for line in lines:
	# tokenize.
	tmp = line.split()
	#tmp1 = tmp[8].split("Target=")
	#tmp2 = tmp1[1].split("-")
	#key = "%s-%s" % (tmp2[0], tmp2[1])
	key = tmp[2].split()[0].replace(">","")

	# Increment count.
	if key in mirbase:
		mirbase[key][1] += 1
	else:
		print key
		print "not found"
		sys.exit()

# Print out summary.
final = []
for key in mirbase:
	rel = float(mirbase[key][1]) / float(mirbase[key][0])
	final.append( ( rel, mirbase[key][0], mirbase[key][1],  key ) )
	
# Sort and print by highest hits.
res = sorted(final, key=itemgetter(0))
res.reverse()

for r in res:
	print "%f\t%i\t%i\t%s" % r
